package com.powernode.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.NoticeConstant;
import com.powernode.domain.Notice;
import com.powernode.mapper.NoticeMapper;
import com.powernode.service.NoticeService;
import com.powernode.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 内容:
 * 作者: cy
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "com.powernode.service.impl.NoticeServiceImpl")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 分页查询公告列表
     * @param page
     * @param notice
     * @return
     */
    @Override
    public Page<Notice> selectNoticePage(Page<Notice> page, Notice notice) {
        return noticeMapper.selectPage(page, new LambdaQueryWrapper<Notice>()
                .eq(notice.getShopId() != 1, Notice::getShopId, notice.getShopId())
                .eq(!ObjectUtils.isEmpty(notice.getStatus()), Notice::getStatus, notice.getStatus())
                .eq(!ObjectUtils.isEmpty(notice.getIsTop()), Notice::getIsTop, notice.getIsTop())
                .like(StringUtils.hasText(notice.getTitle()), Notice::getTitle, notice.getTitle())
                .orderByDesc(Notice::getPublishTime)
        );
    }
    /**
     * 新增公告
     * @param notice
     */
    @Override
    @CacheEvict(key = NoticeConstant.NOTICE_FRONT_PREFIX)
    public void addNotice(Notice notice) {
        Long userId = AuthUtil.getUserIdOrShopId(true);
        log.info("新增公告{}，用户id为{}，店铺id为{}", JSON.toJSONString(notice), userId, notice.getShopId());
        notice.setUpdateTime(new Date());
        if (notice.getStatus()) {
            notice.setPublishTime(new Date());
        }
        noticeMapper.insert(notice);
    }


    /**
     * 查询前台置顶公告
     *
     * @return
     */
    @Override
    @Cacheable(key = NoticeConstant.NOTICE_FRONT_PREFIX)
    public List<Notice> selectFrontNotice() {
        return noticeMapper.selectList(new LambdaQueryWrapper<Notice>()
                .select(Notice::getTitle)
                .eq(Notice::getStatus, 1)
                .eq(Notice::getIsTop, 1)
                .orderByDesc(Notice::getPublishTime)
        );
    }
}
